import axios from "axios";
import router from "@/router/index.js";
import { showDialog } from "vant";
import api from "@/api/login.js";
import { setLoginInfo, removeLoginInfo } from "@/utils/loginInfo.js";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, //基础路径上会携带/api
  timeout: 5000,
});

// 是否正在刷新的标记
let isRefreshing = true;
//重试队列
let requests = [];
// let requestCount = 0;

//请求预处理
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("accessToken"); //getToken是在另一个JS文件中封装好的方法
    token && (config.headers["Authorization"] = token);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptors
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 401 && !response.config.noToken) {
      if (isRefreshing) {
        updateToken();
        isRefreshing = false;
        requests.push(() => {
          resolve(service(response));
        });
      }
    }
    return response && response.data;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);

// 刷新token
async function updateToken() {
  const loginInfo = localStorage.getItem("loginInfo");
  if (loginInfo) {
    const res = await api.refreshToken(JSON.parse(loginInfo));
    if (res.data.code === 0) {
      await setLoginInfo(res.data); // 设置登录信息
      requests.map((callback) => {
        callback();
      });
      isRefreshing = true;
    } else {
      toLogin();
    }
  } else {
    toLogin();
  }
}
// 前往登录页面 清空状态
function toLogin() {
  showDialog({
    message: "登录失效,请重新登录",
  }).then(() => {
    removeLoginInfo();
    requests = [];
    isRefreshing = true;
    router.push("/login");
  });
}

export default service;
